﻿using System;
using System.Diagnostics;
using PipeTest.Win32;

namespace PipeTest.Game
{
    public class GameVistor
    {
        private PipeClient pipeClient;

        private string pipeName;

        private int pid;

        private IntPtr mainWindowHandle;

        public PipeClient PipeClient
        {
            get { return pipeClient; }
            set { pipeClient = value; }
        }

        public string PipeName
        {
            get { return pipeName; }
            set { pipeName = value; }
        }

        public int Pid
        {
            get { return pid; }
            set { pid = value; }
        }

        public GameVistor(int pid)
        {
            this.pid = pid;
            Process process= Process.GetProcessById(pid);
            mainWindowHandle = process.MainWindowHandle;
            pipeName = string.Format("\\\\.\\pipe\\DInput-{0}", pid);
            pipeClient = new PipeClient(pipeName);
            pipeClient.Connect();
        }

        public void SendKey(int key)
        {
            if (pipeClient != null)
            {
                pipeClient.WriteKey(key);
            }
        }

        public void Dispose()
        {
            if (pipeClient != null)
            {
                pipeClient.Disconnect();
            }
        }

        public void BringupWindow()
        {
            NativeMethod.SetForegroundWindow(mainWindowHandle);
            NativeMethod.ShowWindow(mainWindowHandle, 1);
        }
    }
}
